package abg.core.service.mt.impl;


import abg.core.common.security.AuthUser;
import abg.core.common.security.AuthKit;
import abg.core.common.util.StringKit;
import abg.core.domain.db.MtRoomApply;
import abg.core.domain.db.SysUser;
import abg.core.domain.mt.MtRoomApplyVo;
import abg.core.domain.search.Psh;
import abg.core.domain.sys.MSG;
import abg.core.domain.sys.ServiceException;
import abg.core.mapper.MtRoomApplyMapper;
import abg.core.mapper.SysUserMapper;
import abg.core.service.mt.MtRoomApplyService;
import abg.core.service.sys.SysDictService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

import static abg.core.domain.db.table.MtRoomApplyTableDef.MT_ROOM_APPLY;
import static abg.core.domain.db.table.SysUserTableDef.SYS_USER;

/**
 * 会议室相关功能服务类
 *
 * @author leyili
 */
@Slf4j
@Service
public class MtRoomApplyServiceImpl implements MtRoomApplyService {

    @Resource
    private SysUserMapper sysUserMapper;


    @Resource
    private MtRoomApplyMapper mtRoomApplyMapper;

    @Resource
    private SysDictService dictService;

    /**
     * 申请会议室资格
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addApply(MtRoomApply param) {
        AuthUser currentUser = AuthKit.mastLogin();

        // 最大申请人数
        int mtApplyUserMaxCount = Integer.parseInt(dictService.getString("mt_apply_user_max_count", "600"));
        if (param.getUserMaxCount() > mtApplyUserMaxCount) {
            throw new ServiceException("申请人数不能大于" + mtApplyUserMaxCount);
        }

        //校验是否有待审核记录
        QueryWrapper check1 = QueryWrapper.create().from(MtRoomApply.class).where(MT_ROOM_APPLY.USER_ID.eq(currentUser.getUserId())).where(MT_ROOM_APPLY.APPLY_STATUS.eq("0")).where(MT_ROOM_APPLY.DEL.eq("0")).limit(1);
        MtRoomApply mtRoomApplyCheck1 = mtRoomApplyMapper.selectOneByQuery(check1);
        if (mtRoomApplyCheck1 != null) {
            throw new ServiceException(MSG.MT_ROOM_APPLY_HAS_TO_BE_REVIEWED);
        }
        // 校验是否有通过审核并且没到期的记录
        QueryWrapper check2 = QueryWrapper.create().from(MtRoomApply.class).where(MT_ROOM_APPLY.USER_ID.eq(currentUser.getUserId())).where(MT_ROOM_APPLY.APPLY_STATUS.eq("1")).where(MT_ROOM_APPLY.APPLY_CLOSE_TIME.ge(new Date())).where(MT_ROOM_APPLY.DEL.eq("0")).limit(1);
        MtRoomApply mtRoomApplyCheck2 = mtRoomApplyMapper.selectOneByQuery(check2);
        if (mtRoomApplyCheck2 != null) {
            throw new ServiceException(MSG.MT_ROOM_APPLY_HAS_MT_AUTH);
        }

        //填充数据
        param.setApplyStatus("0");
        param.setUserId(currentUser.getUserId());
        int i = mtRoomApplyMapper.insertSelective(param);
        return true;
    }


    @Override
    public Page<MtRoomApplyVo> page(MtRoomApplyVo mtRoomApply, Psh psh) {
        QueryWrapper wrapper = QueryWrapper.create().select(MT_ROOM_APPLY.ALL_COLUMNS)
                .from(MtRoomApply.class)
                .leftJoin(SysUser.class)
                .on(MT_ROOM_APPLY.USER_ID.eq(SYS_USER.ID))
                .select(SYS_USER.ACCOUNT, SYS_USER.PHONE, SYS_USER.ID_CARD_NAME)
                // 根据 用户ID 查询
                .where(MT_ROOM_APPLY.USER_ID.eq(mtRoomApply.getUserId()))
                // 根据用户账号查询
                .and(SYS_USER.ACCOUNT.eq(mtRoomApply.getAccount()))
                // 根据用户手机号查询
                .and(SYS_USER.PHONE.eq(mtRoomApply.getPhone()))
                // 根据用户身份证姓名查询
                .and(SYS_USER.ID_CARD_NAME.eq(mtRoomApply.getIdCardName()))
                // 根据审批状态查询
                .and(MT_ROOM_APPLY.APPLY_STATUS.eq(mtRoomApply.getApplyStatus()))
                // 创建时间倒序/审批状态正序
                .orderBy(MT_ROOM_APPLY.CT.desc(), MT_ROOM_APPLY.APPLY_STATUS.asc());

        // 根据申请时间查询
        if (StringKit.isNotBlank(psh.getTime1())) {
            wrapper.and(MT_ROOM_APPLY.CT.between(psh.getTime1().split(",")[0], psh.getTime1().split(",")[1]));
        }
        // 根据审批时间查询
        if (StringKit.isNotBlank(psh.getTime2())) {
            wrapper.and(MT_ROOM_APPLY.UT.between(psh.getTime2().split(",")[0], psh.getTime2().split(",")[1]));
        }

        return mtRoomApplyMapper.paginateAs(psh, wrapper, MtRoomApplyVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object approve(MtRoomApply mtRoomApply) {

        MtRoomApply mtRoomApplyUpdate = new MtRoomApply();
        mtRoomApplyUpdate.setId(mtRoomApply.getId());
        mtRoomApplyUpdate.setApplyStatus(mtRoomApply.getApplyStatus());
        mtRoomApplyUpdate.setApplyCloseTime(mtRoomApply.getApplyCloseTime());
        mtRoomApplyUpdate.setProcessMsg(mtRoomApply.getProcessMsg());
        mtRoomApplyUpdate.setUserMaxCount(mtRoomApply.getUserMaxCount());
        mtRoomApplyMapper.update(mtRoomApplyUpdate);

        // 如果是审核通过状态 修改user表 mt_auth
        if ("1".equals(mtRoomApply.getApplyStatus())) {
            // 校验用
            MtRoomApply maCheck = mtRoomApplyMapper.selectOneById(mtRoomApply.getId());
            SysUser sysUser = new SysUser();
            sysUser.setId(maCheck.getUserId());
            sysUser.setMtAuth("1");
            sysUserMapper.update(sysUser);
        }

        return true;
    }
}
